using System;

namespace NRehersal
{
    public class TestRunner : IDisposable
    {
        private readonly RehersalBase testClass;

        static TestRunner()
        {
            TestOverrides.SingleTestRunMethod=RunSingleTest;
        }

        public TestRunner(RehersalBase classWithTests)
        {
            testClass = classWithTests;
        }

        public void Dispose()
        {
            RunTests();
        }



        internal void RunTests()
        {

            testClass.onceBeforeAllTests();
            
            foreach (TestData test in testClass.Tests)
            {
                TestOverrides.SingleTestRunMethod(test,testClass);
            }
            testClass.onceAfterAllTests();

        }

        private static void RunSingleTest(TestData test,RehersalBase testClass)
        {
            try
            {
                testClass.onceBeforeEachTest();
                test.Code();
            }
            catch (Exception e)
            {
                Console.WriteLine("Test [{0}] Threw an exception:", test.Name);
                Console.WriteLine(e);
            }
            finally
            {
                testClass.onceAfterEachTest();
            }
        }
    }
}